<template>
  <div class="user-detail">
<!--    修改跟人信息弹框-->
    <el-dialog title="编辑个人信息" :visible.sync="dialogFormVisible">
      <el-form :model="userDetail">
        <el-form-item >
          <el-input v-model="userDetail.username" placeholder="昵称" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="userDetail.school" placeholder="学校" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="userDetail.course" placeholder="专业" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input type="textarea" v-model="userDetail.description" placeholder="个人说明" :autosize="{minRows:1,maxRows:4}" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false;updateUser()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="发送私信" :visible.sync="dialogMailVisible">
      <el-form :model="MailDetail"  label-width="80px" style="text-align: left">
        <el-form-item label="发给">
          <span>{{userDetail.username}}</span>
          <el-input v-model="MailDetail.to" autocomplete="off" v-show="false"></el-input>
        </el-form-item>
        <el-form-item label="主题">
          <el-input v-model="MailDetail.title"  maxlength="20" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="MailDetail.text"  :autosize="{minRows:4,maxRows:8}" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMailVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendMail()">确 定</el-button>
      </div>
    </el-dialog>

    <div class="user-header">
      <div style="width:66%;margin: auto;position: relative;">
        <el-link @click="dialogFormVisible = true" v-if="$route.params.id==loginUser().id" style="float: right;color: white" :underline="false" icon="el-icon-edit-outline fa-lg">编辑</el-link>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/main/home' }"><span style="color: #ffffff;">首页</span></el-breadcrumb-item>
          <el-breadcrumb-item ><span style="color: #ffffff;">个人主页</span></el-breadcrumb-item>
        </el-breadcrumb>
        <div style="text-align: left;margin-top: 20px;" >
          <div  @dblclick="clickAvater" style="float: left;overflow: hidden;">
            <el-avatar size="large" :src="'/api/user/download/'+userDetail.avatarId"></el-avatar>

          </div>
          <input type="file" ref="ImageFile" accept="image/*" @change="getImageFile" style="display: none">
          <div style="display: inline-block;vertical-align: top;height: 120px;margin-left: 20px;padding-top: 7px;color: #738792;">
            <span style="vertical-align: top;font-size: 20px;color: #c177e8;">{{userDetail.username}}</span>
             <el-link @click="dialogMailVisible = true;" v-if="$route.params.id!=loginUser().id" style="margin-left: 40px;color: white" :underline="false" icon="el-icon-message fa-lg">私信</el-link>

            <span style="height: 28px;display: block;margin-top: 10px;margin-bottom: 10px;font-size: 90%;">{{userDetail.description}}</span>
<!--           <span style="display: block;vertical-align: bottom;margin-top: 12px;"></span>-->
            <span style="vertical-align: bottom;display: block;">

              <i class="fa fa-university"></i> {{userDetail.school}}
              &nbsp;&nbsp;&nbsp;&nbsp;
              <i class="fa fa-address-card-o"></i> {{userDetail.course}}
            </span>

          </div>
          <div style="position: absolute;bottom: 60px;right: 5px;padding: 5px;">
            Rating: <span style="color: #c177e8">{{userDetail.rating}}</span>
          </div>
          <div style="border-color: #738792;color: #738792;position: absolute;bottom: 20px;right: 5px;font-size: 70%;border-style: solid;padding: 5px;border-radius: 4px;border-width: 1px;">
            最近上线时间：{{$MyUtils.timeToString(lastLoginSession.createTime)}}
          </div>
        </div>

      </div>



    </div>


    <div style="width: 102%;margin-left: -2%;">
      <el-tabs type="border-card">
        <el-tab-pane :label="isOnlyMe()?'我的提交':'TA的提交'" >
          <div class="user-tabs">
            <ul class="user-submit">
              <li>
                <div class="user-progress">{{submitProgress.submitProblemCount}}</div>
                题已挑战
              </li>
              <li style="border-left: 1px solid #e9e9e9;">
                <div class="user-progress">{{submitProgress.acceptProblemCount}}</div>
                题已通过</li>
              <li style="border-left: 1px solid #e9e9e9;">
                <div class="user-progress">{{submitProgress.submitCount}}</div>
                次提交</li>
              <li style="border-left: 1px solid #e9e9e9;">
                <div class="user-progress">{{submitProgress.submitCount>0?(new Number(submitProgress.acceptSubmitCount/submitProgress.submitCount*100).toFixed(2)):0}}%</div>
                通过率</li>
            </ul>
            <submitList  :query="{'userId':this.$route.params.id}"></submitList>
          </div>

        </el-tab-pane>
        <el-tab-pane :label="isOnlyMe()?'我的比赛':'TA的比赛'">
          <div class="user-tabs">
            <ul class="user-submit">
              <li>
                <div class="user-progress" style="color: #ea0e07">{{userDetail.rating}}</div>
                Rating
              </li>
              <li style="border-left: 1px solid #e9e9e9;">
                <div class="user-progress">{{ contestProgress.rank }}</div>
                Rating排名</li>
              <li style="border-left: 1px solid #e9e9e9;">
                <div class="user-progress">{{contestProgress.registerCount}}</div>
                次报名
              </li>
              <li style="border-left: 1px solid #e9e9e9;">
                <div class="user-progress">{{contestProgress.joinCount}}</div>
                次参加</li>
            </ul>
            <h4 style="text-align: left;margin-left: 10px;">我的比赛 </h4>
            <ul class="user-contest">

              <li v-for="(item) in userContestList" :key="item.id" disabled :style="item.status!=0?'color:grey;':''">

                <el-image
                    style="width: 100px; height: 100px"
                    :src="item.contest.avatarId?'/api/user/download/'+item.avatarId:require('@/assets/logo.png')"
                    fit="fit"></el-image>
                <div style="margin-left: 10px;">
                  <div>
                    <!-- 比赛状态 -->
                    <h3><router-link :to="'/main/contest/detail/'+item.contest.id" :style="item.status!=0?'color:grey;':''">{{ item.contest.title }}</router-link></h3>
                    <el-tag class="status" v-if="item.contest.status==0"  size="mini" type="success" effect="dark">未开始</el-tag>
                    <el-tag class="status" v-if="item.contest.status==1"  size="mini" type="danger" effect="dark">进行中</el-tag>
                    <el-tag class="status" v-if="item.contest.status==2"  size="mini" type="info" effect="dark">已结束</el-tag>


                  </div>
                  <!-- 比赛信息 -->
                  <div class="contest-text">
                    <div style="width: 350px;"><i class="fa fa-bell-o"></i>： {{item.contest.startTime}} 至 {{ item.contest.endTime }}(时长{{ getTimeDuration(item.contest.startTime,item.contest.endTime) }})</div>

                  </div>
                  <div style="width: 350px;font-size: 85%">
                    <span><span style="color: #ababab;">AC数量: </span>{{item.userId}} / {{item.contest.problems.length}} </span>
                  </div>

                </div>



              </li>
            </ul>
            <!--分页-->
            <div class="page" v-show="userContestTotal>userContestParams.size">
              <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="userContestTotal"
                  :page-size="userContestParams.size"
                  @current-change="chg"
              >
              </el-pagination>
            </div>
          </div>


        </el-tab-pane>

        <el-tab-pane :label="isOnlyMe()?'我的错题':'TA的错题'">
          <div class="user-tabs">
            <el-empty v-show="NotAcceptProblemTotal==0" description="还没有错题"></el-empty>
            <el-table v-show="NotAcceptProblemTotal>0"
                :data="NotAcceptProblemList"
                style="width: 100%" >
              <el-table-column :label="$t('problemMode.id')" width="120" sortable="custom" prop="code">
                <template slot-scope="scope" >

                  <router-link :to="'/main/problem/detail/'+scope.row.id" target="_blank">{{ $MyUtils.formatCode(scope.row.code) }}</router-link>

                </template>
              </el-table-column>
              <el-table-column :label="$t('problemMode.title')" sortable="custom" width="400" prop="title">
                <template slot-scope="scope" >

                  <router-link :to="'/main/problem/detail/'+scope.row.id" target="_blank">{{ scope.row.title }}</router-link>
                </template>
              </el-table-column>

              <el-table-column :label="$t('problemMode.tags')"  width="140">
                <template slot-scope="scope" >

                  <el-tag
                      v-for="tag in scope.row.tags"
                      :key="tag.id"

                      type="" :color="tag.color">
                    {{tag.name}}
                  </el-tag>

                </template>
              </el-table-column>
              <!-- 困难等级 -->
              <el-table-column :label="$t('problemMode.difficulty')" sortable="custom"  width="140" prop="difficulty">
                <template slot-scope="scope" >
                  <el-rate
                      v-model="scope.row.difficulty"
                      disabled
                      show-score
                      text-color="#ff9900"
                      score-template="{value}">
                  </el-rate>

                </template>
              </el-table-column>
              <el-table-column label="运行结果" align="center" width="100" >

                <template slot-scope="scope" >
                    <div v-html=" $MyUtils.getSubmitResult(scope.row.submit.errorStatus)"></div>
                </template>
              </el-table-column>


            </el-table>
            <!--分页-->
            <div class="page"  v-show="NotAcceptProblemTotal>problemParams.size">
              <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="NotAcceptProblemTotal"
                  :page-size="problemParams.size"
                  :page-sizes="[10,20,30,50,100]"
                  @current-change="chgProblem" >
              </el-pagination>

              </div>

          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import * as userApi from '@/api/admin'
import * as submitApi from '@/api/submit'
import * as contestApi from '@/api/contest'
import * as problemApi from '@/api/problem'
import * as commentApi from "@/api/comment"
import {isLogin,isAdmin,loginUser,setLoginUser} from "@/utils/auth";
export default {
  name: "userDetail",
  data(){
    return {
      MailDetail:{},
      dialogMailVisible:false,
      dialogFormVisible:false, //编辑个人信息弹出框
      userDetail:{},
      submitProgress:{}, //提交统计
      contestProgress:{}, //比赛统计
      loginUserDetail:null,
      // 参加过的比赛
      userContestList:[],  //用户报名过的比赛
      userContestTotal:0,
      userContestParams:{
        userId:this.$route.params.id,
        page:1,
        size:10,
      },
      // 错题
      NotAcceptProblemList:[],
      NotAcceptProblemTotal:0,
      problemParams:{
        accept:1,
        size:10,
        page:1,
      },
      lastLoginSession:{},
      // contestNames:{},  //比赛名称
    }
  },
  components:{
    submitList: () => import('@/components/users/submitList.vue'),
  },
  methods:{
    //当页数发生变化时执行
    chg(curpage) {
      //更新查询的页数
      this.userContestParams.page = curpage;
      //重新查询
      this.getRegisterContestList(this.userContestParams);
    },
    //当页数发生变化时执行
    chgProblem(curpage) {
      //更新查询的页数
      this.problemParams.page = curpage;
      //重新查询
      this.getNotAcceptProblemList();
    },
    updateUser(){//用户个人信息修改
      userApi.loginUpdateById(this.userDetail).then(res=>{
        if(res.data.success){
          this.$message({type:"success",message:"修改成功"});
          //如果是自己，也要修改
          if(this.loginUserDetail.id==this.$route.params.id){
            this.loginUserDetail.username = this.userDetail.username;
            this.loginUserDetail.avatarId = this.userDetail.avatarId;
            this.loginUserDetail.school = this.userDetail.school;
            this.loginUserDetail.course = this.userDetail.course;
            this.loginUserDetail.description = this.userDetail.description
            setLoginUser(this.loginUserDetail);
          }
        }else {
          this.getUserDetail();
        }
      })
    },
    //获取报名过的比赛
    getRegisterContestList(){
      contestApi.getContestRegisterSearch(this.userContestParams).then(res=>{
        if(res.data.success){
          this.userContestList = res.data.data.dataList;
          this.userContestTotal = res.data.data.total;
        }
      })
    },
    //获取错题列表
    getNotAcceptProblem(){
      problemApi.getListData(this.problemParams).then(async res=>{
        if(res.data.data){
          var tables = res.data.data.dataList;
          for(var i = 0;i<tables.length;i++){  //获取最后一次提交记录
            await problemApi.getLastSubmit({"id":tables[i].id,"userId":this.$route.params.id}).then(res1=>{
              tables[i].submit = res1.data.data;
            })
          }
          this.NotAcceptProblemList = tables;
          this.NotAcceptProblemTotal = res.data.data.total;
        }
      })
    },
    //比赛统计
    getContestProgress(){
      contestApi.getProgress({"userId":this.$route.params.id}).then(res=>{
        if(res.data.success){
          this.contestProgress = res.data.data;
        }
      })
    },
    //做题分析
    rightProgress(){
      submitApi.submitProgress({"userId":this.$route.params.id}).then(res=>{
        if(res.data.success){
          this.submitProgress = res.data.data;
        }
      })
    },
    //双击头像，更换
    clickAvater(){
      if(this.isOnlyMe()){
        this.$refs.ImageFile.click(); //上传文件弹出框
      }
    },
    //获取图片文件
    async getImageFile(event){
      // console.info(event.target.files);
      if(event.target.files[0]&&event.target.files[0].name){
        var imageFile = event.target.files[0];
        // this.problemFileName  = event.target.files[0].name;
        // this.uploadFileFlag = true;
        let form = new FormData();
        form.append('file', imageFile);
        //上传图片
        const res = await userApi.uploadImage(form).then(res=>{
          return res.data.data;
        })
        this.userDetail.avatarId = res;
        this.userDetail = JSON.parse(JSON.stringify(this.userDetail))
        //调用修改用户接口
        this.updateUser();
        // console.info(this.userDetail);
      }
      // if(event.target.files[1])this.outputFile = event.target.files[1].name;
    },
    isOnlyMe(){  //判断主页是否为自己
      return this.$route.params.id==this.loginUser().id;
    },
    loginUser(){
      if(this.loginUserDetail)return this.loginUserDetail;
      // console.info(this.$MyUtils)
      if(!isLogin()) {

        return this.loginUserDetail = {};
      }
      return this.loginUserDetail = loginUser();
    },
    isEdit(){  //允许修改 ，自己或管理
      if(isAdmin()||(isLogin()&&loginUser().id==this.$route.params.id)){
        return true;
      }
      return false;
    },
    getUserDetail(){
      if(isLogin()&&loginUser().id==this.$route.params.id){  //表示访问的是自己
        this.userDetail = loginUser();
        return;
      }
      userApi.getEasyUserById({"id":this.$route.params.id}).then(res=>{
        this.userDetail = res.data.data;
      })
    },
    // 获取时间差
    getTimeDuration(time1,time2){
      var x = new Date(time2).getTime()-new Date(time1).getTime(); //毫秒
      var min = Math.floor(x/1000/60);  //分钟
      var hour = Math.floor(min/60);
      var res = "";
      if(hour!=0)res+=hour + '小时';
      if(min%60!=0)res += (min%60)+"分钟";
      return res;
    },
    getLastSession(){//获取最后登录记录
      userApi.getLastLoginSession({"userId":this.$route.params.id}).then(res=>{
        if(res.data.data){
          this.lastLoginSession = res.data.data;
        }else{
          this.lastLoginSession = {createTime:"1970-01-01 00:00:00"};
        }
      })
    },
    sendMail(){  //发私信
      this.MailDetail.to = this.$route.params.id;
      commentApi.sendMail(this.MailDetail).then(res=>{
        if(res.data.success){
          this.$message({type:"success",message:"发送成功"});
          this.MailDetail = {};
          this.dialogMailVisible = false;
        }
      })
    },
  },
  created() {
    this.getUserDetail();
    this.rightProgress();//做题分析
    this.getContestProgress(); //比赛分析
    this.getRegisterContestList();  //报名过比赛列表
    this.getNotAcceptProblem();
    this.getLastSession();

  }
}
</script>
<style scoped>
.user-detail .user-header{
  background-color: #3c5867;
  width: 102%;
  color: white;
  margin-left: -2%;
  padding-top: 10px;
}
</style>
<style >
.user-detail .user-header .el-avatar--large{
  width:100px;
  height: 100px;
}
.user-detail .user-tabs{
  width: 66%;
  margin: auto;
}
.user-detail .user-tabs .user-submit{
  list-style: none;
  margin: 20px 0px 20px 0px;
  padding: 0;
}
.user-detail .user-tabs .user-submit li{
  display: inline-block;
  padding: 20px 60px 20px 60px;

}



.user-detail .user-tabs .user-submit li .user-progress{
  font-size: 20px;
  font-weight: 500;
  padding: 10px;
}


.user-detail .user-tabs .user-contest{
  list-style: none;
  margin: 20px 0px 20px 0px;
  padding: 0;
}

.user-detail .user-tabs .user-contest li{
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: inline-block;
  width: 470px;
  /* list-style: none; */
  margin-top: 10px;
  padding: 15px;
  background-color: #ffffff;
  text-align: left;
  border-radius: 10px;
  vertical-align: top;
  overflow: hidden;
  min-width: 410px;
  margin: 10px;
}
.user-detail .user-tabs .user-contest li > div{
  float: left;
  /* margin-left: 5px; */
}
.user-detail .user-tabs .user-contest li h3{
  display: inline-block;
  margin-top: 2px;
  position: relative;
  margin-bottom: 0px;
  font-weight: 400;
  font-size: 15px;

  /* float: left; */
}
.user-detail .user-tabs .user-contest li .contest-text{
  font-size: 14px;
  margin-top: 7px;
  /* float: left; */
}

.user-detail .user-tabs .user-contest li .contest-text > div{
  margin-top: 5px;
  margin-bottom: 5px;
  /* float: left; */
}
.user-detail .user-tabs .user-contest li .status{
  /* font-size: 65%; */
  /* margin-top: -5px; */
  margin-left: 5px;
  /* border-radius: 0px; */
}

</style>
<style>
.user-detail .el-tabs__nav.is-top{
  margin-left: 20%;
}
</style>
